package com.comdosoft.comdoandroidbase.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.comdosoft.comdoandroidbase.R;
import com.comdosoft.comdoandroidbase.adapter.PullToRefreshAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yewei on 2015/9/17.
 */
public class PullToRreshFragment extends Fragment {

    private PullToRefreshListView ptrListView;
    private int page = 1;
    private List<String> mList = new ArrayList<String>();
    private PullToRefreshAdapter mAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pulltorefresh, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        ptrListView = (PullToRefreshListView) view.findViewById(R.id.id_ptr);
        ptrListView.setMode(PullToRefreshBase.Mode.BOTH);
        ptrListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (refreshView.isHeaderShown()) {
                    // 上拉刷新
                    page = 1;
                    getData(page);
                    mAdapter.notifyDataSetChanged();
                    ptrListView.onRefreshComplete();
                } else if (refreshView.isFooterShown()) {
                    // 下拉加载更多
                    page++;
                    getData(page);
                    mAdapter.notifyDataSetChanged();
                    ptrListView.onRefreshComplete();

                }
            }
        });
        ptrListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 点击事件
            }
        });
        getData(page);
        mAdapter = new PullToRefreshAdapter(getActivity(), mList);
        ptrListView.setAdapter(mAdapter);
    }

    private List<String> getData(int page) {
        mList.clear();
        for (int i = 0; i < page * 10; i++) {
            mList.add("这是第"+i + "个Item");
        }
        return mList;
    }
}
